import { ref, computed } from 'vue'
import { defineStore } from 'pinia'
import { ElMessage } from 'element-plus'

import {
  getAllHistory,
  getHistoryList,
  deleteHistory,
  saveHistory,
  useHistoryInitChat,
} from '@/api/chat-history'
import type { ChatMessage } from '@/types/chat'

// 历史记录项类型
export interface HistoryItem {
  id: string
  sessionId: string
  content: string
  sender: string | number
  timestamp: number
  userId: string
}

// 分页参数类型
export interface HistoryPageParams {
  current?: number
  size?: number
  keyword?: string
}

// 分页结果类型
export interface HistoryPageResult {
  records: HistoryItem[]
  total: number
  current: number
  size: number
}

export const useHistoryStore = defineStore('history', () => {
  // 状态
  const historyList = ref<HistoryItem[]>([])
  const currentHistory = ref<HistoryItem[]>([])
  const currentSessionId = ref<string>('')
  const loading = ref(false)
  const pagination = ref({
    current: 1,
    size: 10,
    total: 0,
  })

  // 类型转换辅助函数
  const convertHistoryItemToChatMessage = (item: HistoryItem): ChatMessage => {
    return {
      content: item.content,
      sender: item.sender == '1' || item.sender === 'chat' ? 'chat' : 'user',
      timestamp: item.timestamp,
      // images 字段可能需要从 content 中解析或从其他地方获取
    }
  }

  const convertChatMessageToHistoryItem = (
    message: ChatMessage,
    sessionId?: string,
    userId?: string,
  ): Partial<HistoryItem> => {
    return {
      content: message.content,
      sender: message.sender,
      timestamp: message.time || message.timestamp,
      sessionId: sessionId || '',
      userId: userId || '',
      // id 通常由服务器生成
    }
  }

  // 计算属性
  const hasHistory = computed(() => historyList.value.length > 0)
  const isEmpty = computed(() => !loading.value && historyList.value.length === 0)

  // 获取全部历史记录
  const fetchAllHistory = async () => {
    try {
      loading.value = true
      const response = await getAllHistory()
      historyList.value = response.data || []
      return response.data
    } catch (error) {
      console.error('获取历史记录失败:', error)
      ElMessage.error('获取历史记录失败')
      return []
    } finally {
      loading.value = false
    }
  }

  // 分页获取历史记录
  const fetchHistoryPage = async (params: HistoryPageParams = {}) => {
    try {
      loading.value = true
      const queryParams = {
        current: params.current || pagination.value.current,
        size: params.size || pagination.value.size,
        keyword: params.keyword || '',
      }

      const response = await getHistoryList(queryParams)
      const result = response.data as HistoryPageResult

      historyList.value = result.records || []
      pagination.value = {
        current: result.current,
        size: result.size,
        total: result.total,
      }

      return result
    } catch (error) {
      console.error('获取历史记录分页失败:', error)
      ElMessage.error('获取历史记录失败')
      return null
    } finally {
      loading.value = false
    }
  }

  // 将 ChatMessage 转换为 API 需要的格式
  const convertChatMessageToApiFormat = (message: ChatMessage) => {
    return {
      content: message.content,
      sender: message.sender == 1 || message.sender === 'chat' ? 1 : 0,
      time: message.time, // API 可能期望 time 字段
      timestamp: message.time, // 同时提供 timestamp 字段以兼容
      images: message.images,
    }
  }

  // 保存聊天消息到历史记录
  const saveMessage = async (message: ChatMessage) => {
    try {
      // const apiMessage = convertChatMessageToApiFormat(message)
      if (message.sender == 1 || message.sender === 'chat') {
        message.sender = 1
      } else {
        message.sender = 0
      }
      message.timestamp = message.timestamp || message.time
      if (!message.content) {
        return ''
      }
      const response = await saveHistory(message)
      // 保存成功后可以选择刷新历史记录
      return response.data
    } catch (error) {
      console.error('保存历史记录失败:', error)
      ElMessage.error('保存历史记录失败')
      throw error
    }
  }

  // 删除历史记录
  const removeHistory = async (ids: string | string[]) => {
    try {
      const idsStr = Array.isArray(ids) ? ids.join(',') : ids
      const response = await deleteHistory(idsStr)

      // 删除成功后从本地列表中移除
      if (Array.isArray(ids)) {
        historyList.value = historyList.value.filter((item) => !ids.includes(item.id))
      } else {
        historyList.value = historyList.value.filter((item) => item.id !== ids)
      }

      ElMessage.success('删除成功')
      return response.data
    } catch (error) {
      console.error('删除历史记录失败:', error)
      ElMessage.error('删除历史记录失败')
      throw error
    }
  }

  // 通过历史记录初始化聊天
  const initChatFromHistory = async (sessionId: string) => {
    try {
      loading.value = true
      const response = await useHistoryInitChat(sessionId)
      const historyData = response.data.list || []

      // 将历史记录转换为 ChatMessage 格式
      const chatMessages = historyData.map((item: any) => {
        // 兼容不同的数据格式
        if (item.content && typeof item.sender !== 'undefined') {
          return convertHistoryItemToChatMessage({
            id: item.id || '',
            sessionId: item.sessionId || sessionId,
            content: item.content,
            sender: item.sender == 1 || item.sender === 'chat' ? 'chat' : 'user',
            timestamp: item.timestamp || item.timeStamp || item.time || Date.now(),
            userId: item.userId || '',
          })
        }
        return item
      })

      currentHistory.value = historyData
      currentSessionId.value = sessionId
      return chatMessages
    } catch (error) {
      console.error('初始化聊天失败:', error)
      ElMessage.error('加载聊天记录失败')
      throw error
    } finally {
      loading.value = false
    }
  }

  // 搜索历史记录
  const searchHistory = async (keyword: string) => {
    return await fetchHistoryPage({
      current: 1,
      size: pagination.value.size,
      keyword,
    })
  }

  // 清空当前历史记录
  const clearCurrentHistory = () => {
    currentHistory.value = []
    currentSessionId.value = ''
  }

  // 清空所有历史记录（本地状态）
  const clearAllHistory = () => {
    historyList.value = []
    currentHistory.value = []
    currentSessionId.value = ''
    pagination.value = {
      current: 1,
      size: 10,
      total: 0,
    }
  }

  // 分页相关方法
  const nextPage = async () => {
    if (pagination.value.current * pagination.value.size < pagination.value.total) {
      await fetchHistoryPage({ current: pagination.value.current + 1 })
    }
  }

  const prevPage = async () => {
    if (pagination.value.current > 1) {
      await fetchHistoryPage({ current: pagination.value.current - 1 })
    }
  }

  const goToPage = async (page: number) => {
    await fetchHistoryPage({ current: page })
  }

  // 根据 ID 查找历史记录
  const findHistoryById = (id: string): HistoryItem | undefined => {
    return historyList.value.find((item) => item.id === id)
  }

  // 根据 sessionId 查找历史记录
  const findHistoryBySessionId = (sessionId: string): HistoryItem[] => {
    return historyList.value.filter((item) => item.sessionId === sessionId)
  }

  return {
    // 状态
    historyList,
    currentHistory,
    currentSessionId,
    loading,
    pagination,

    // 计算属性
    hasHistory,
    isEmpty,

    // 方法
    fetchAllHistory,
    fetchHistoryPage,
    saveMessage,
    removeHistory,
    initChatFromHistory,
    searchHistory,
    clearCurrentHistory,
    clearAllHistory,
    nextPage,
    prevPage,
    goToPage,
    findHistoryById,
    findHistoryBySessionId,

    // 类型转换函数
    convertHistoryItemToChatMessage,
    convertChatMessageToHistoryItem,
  }
})
